<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="sumchartData"
          >累计金额</el-button
        >
        <span>{{ totalAmount }}</span>
      </el-col>
    </el-row>
    <div ref="chart" style="width: 100%; height: 600px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  data() {
    return {
      totalAmount: 0,
      chart: null,
      symbolSize: 14,
      targetMonth: "2025-03",
      chartData: [],
      graphicElements: [],
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    // 初始化图表
    async initChart() {
      try {
        await this.generateChartData();
        this.createChartInstance();
        this.setChartOption();
        this.initDraggableControllers();
        this.bindChartEvents();
      } catch (error) {
        console.error("图表初始化失败:", error);
      }
    },

    // 生成图表数据
    generateChartData() {
      return new Promise((resolve) => {
        const date = new Date(`${this.targetMonth}-01`);
        const lastDay = new Date(
          date.getFullYear(),
          date.getMonth() + 1,
          0
        ).getDate();

        this.chartData = Array.from({ length: lastDay }, (_, i) => {
          const d = new Date(date.getFullYear(), date.getMonth(), i + 1);
          return [d.toISOString().split("T")[0], 10000];
        });
        resolve();
      });
    },

    // 创建图表实例
    createChartInstance() {
      if (this.chart) this.chart.dispose();
      this.chart = echarts.init(this.$refs.chart);
    },

    // 设置图表配置
    setChartOption() {
      const option = {
        title: {
          text: `${this.targetMonth} 每日目标调整`,
          left: "center",
          textStyle: {
            fontSize: 18,
            color: "#333",
          },
        },
        tooltip: {
          triggerOn: "none",
          formatter: (params) => {
            return `日期：${
              params.data[0]
            }<br>目标值：￥${params.data[1].toFixed(2)}`;
          },
        },
        grid: {
          top: "15%",
          bottom: "20%",
        },
        xAxis: {
          type: "category",
          data: this.dateLabels,
          name: "日期",
          axisLabel: {
            rotate: 45,
            formatter: (val) => val.slice(5),
            margin: 15,
          },
        },
        yAxis: {
          min: 0,
          max: 30000,
          type: "value",
          name: "目标值（元）",
          axisLabel: {
            formatter: (value) => `￥${value.toFixed(0)}`,
          },
        },
        dataZoom: [
          {
            type: "slider",
            xAxisIndex: 0,
            start: 0,
            end: 100,
            bottom: "5%",
          },
          {
            type: "inside",
            xAxisIndex: 0,
          },
        ],
        series: [
          {
            id: "mainSeries",
            type: "line",
            data: this.chartData,
            // 新增关键配置
            animation: false, // 禁用动画防止闪烁
            itemStyle: {
              emphasis: {
                borderWidth: 3, // 强化悬停效果
              },
            },
          },
        ],
      };
      this.chart.setOption(option);
    },

    // 初始化拖拽控制器（重点修改部分）
    initDraggableControllers() {
      this.graphicElements = this.chartData.map((item, index) => ({
        type: "circle",
        position: this.chart.convertToPixel("grid", item),
        shape: { cx: 0, cy: 0, r: this.symbolSize / 2 },
        style: { fill: "transparent" }, // 保持可见调试
        draggable: true,
        invisible: false, // 确保元素可见
        zlevel: 10,
        ondrag: (e) => {
          this.handleDrag(index, [e.offsetX, e.offsetY]);
        },

        onmousemove: (e) => {
          this.showTooltip(index);
        },
        onmouseout: (e) => {
          this.hideTooltip(index);
        },
        z: 100,
      }));

      this.chart.setOption({ graphic: this.graphicElements });
    },

    // 处理拖拽事件（优化版本）
    handleDrag(index, pixelPos) {
      try {
        const dataPoint = this.chart.convertFromPixel("grid", pixelPos);
        const clampedY = Math.max(0, Math.min(dataPoint[1], 30000));

        // 使用Vue.set保证响应式更新
        this.$set(this.chartData, index, [
          this.chartData[index][0],
          Number(clampedY.toFixed(2)),
        ]);
        //打印
        console.log(index);
        console.log(this.chartData[index][0]);
        console.log(Number(clampedY.toFixed(2)));
        // 批量更新提升性能
        this.$nextTick(() => {
          this.updateChart();
          this.updateGraphicPositions();
        });
      } catch (error) {
        console.error("拖拽处理失败:", error);
      }
    },

    sumchartData() {
      this.totalAmount = 0;
      this.chartData.forEach((item) => {
        this.totalAmount += item[1];
      });
    },

    // 在methods中添加
    showTooltip(dataIndex) {
      this.chart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: dataIndex,
      });
    },

    hideTooltip(dataIndex) {
      //   console.log(dataIndex);
      this.chart.dispatchAction({
        type: "hideTip",
      });
    },

    // 更新图表数据
    updateChart() {
      console.log(JSON.stringify(this.chartData));
      this.chart.setOption({
        series: [
          {
            data: this.chartData,
          },
        ],
      });
    },

    // 同步更新图形位置
    updateGraphicPositions() {
      const newGraphic = this.chartData.map((item, index) => ({
        ...this.graphicElements[index],
        position: this.chart.convertToPixel("grid", item),
      }));

      this.chart.setOption({ graphic: newGraphic });
      //   console.log(newGraphic);
    },

    // 绑定图表事件
    bindChartEvents() {
      this.chart.on("dataZoom", this.handleDataZoom);
    },

    // 处理缩放事件
    handleDataZoom() {
      this.$nextTick(this.updateGraphicPositions);
    },

    // 响应窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
        this.updateGraphicPositions();
      }
    },

    // 清理资源
    cleanup() {
      window.removeEventListener("resize", this.handleResize);
      if (this.chart) {
        this.chart.off("dataZoom", this.handleDataZoom);
        this.chart.dispose();
      }
    },
  },
};
</script>

<style>
/* 增强拖拽点可视性（调试时可启用） */
.echarts-graphic-element {
  stroke: rgba(255, 0, 0, 0.3);
  stroke-width: 2px;
}
</style>